package com.nj9you.sdk.pay;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.nj9you.sdk.constant.Constants;
import com.nj9you.sdk.framework.IPayFunction;
import com.nj9you.sdk.framework.PayResult;
import com.nj9you.sdk.framework.ResponseCallback;
import com.nj9you.sdk.http.Response;
import com.nj9you.sdk.params.PayParams;
import com.nj9you.sdk.request.IPayRequest;
import com.nj9you.sdk.utils.AlipayHelper;
import com.nj9you.sdk.utils.Log;
import com.nj9you.sdk.utils.Utils;

import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.Map;

/**
 * 阿里支付模块
 */
public class Alipay implements IPay {

    private Context mContext;
    private IPayFunction mPayFunction;
    private PrivateHandler mPrivateHandler;

    @Override
    public void init(Context context, IPayFunction f) {
        mContext = context;
        mPayFunction = f;
        mPrivateHandler = new PrivateHandler(context, this);
    }

    @Override
    public void pay(PayParams payParams) {
        if (payParams == null) {
            if (mPayFunction != null) {
                String desc = mContext.getString(Utils.getStringId(mContext, "jy_null_payparams"));
                mPayFunction.notifyPayResult(PayResult.PAY_FAILURE, desc, this);
            }
            return;
        }
        execPay(payParams);
    }

    @Override
    public String toString() {
        return getPayName();
    }

    static class PrivateHandler extends Handler {
        private WeakReference<Alipay> mAlipay;

        public PrivateHandler(Context context, Alipay alipay) {
            super(context.getMainLooper());
            mAlipay = new WeakReference<Alipay>(alipay);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constants.SDK_PAY_FLAG:
                    // Log.d(Log.TAG, "result : " + msg.obj);
                    if (mAlipay != null && mAlipay.get() != null) {
                        Map<String, String> result = null;
                        try {
                            result = (Map<String, String>) msg.obj;
                        } catch (Exception e) {
                        }
                        mAlipay.get().parseAlipayResult(result);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 解析支付结果
     *
     * @param result
     */
    private void parseAlipayResult(Map<String, String> result) {
        boolean ignoreSignCheck = true; // 不执行签名检查
        AliPayResult payResult = new AliPayResult(result);
        String tradeStatus = payResult.getMemo();
        String resultStatus = payResult.getResultStatus();
        // Log.d(Log.TAG, "tradeStatus : " + tradeStatus);
        // 支付成功状态
        if ("9000".equals(resultStatus)) { // 订单支付成功
            AlipayChecker checker = new AlipayChecker(payResult);
            int ret = checker.checkSignV2();
            if (ret == AlipayChecker.RESULT_CHECK_SIGN_SUCCEED || ignoreSignCheck) {
                if (mPayFunction != null) {
                    mPayFunction.notifyPayResult(PayResult.PAY_SUCCESS, tradeStatus, this);
                }
            } else {
                if (mPayFunction != null) {
                    String desc = mContext.getString(Utils.getStringId(mContext, "jy_check_sign_failed"));
                    mPayFunction.notifyPayResult(PayResult.PAY_FAILURE, desc, this);
                }
            }
        } else if ("8000".equals(resultStatus)) { // 正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
            if (mPayFunction != null) {
                mPayFunction.notifyPayResult(PayResult.PAY_WAITING, tradeStatus, this);
            }
        } else if ("6001".equals(resultStatus)) { // 用户中途取消
            if (mPayFunction != null) {
                mPayFunction.notifyPayResult(PayResult.PAY_CANCEL, tradeStatus, this);
            }
        } else {
            if (mPayFunction != null) {
                mPayFunction.notifyPayResult(PayResult.PAY_FAILURE, tradeStatus, this);
            }
        }
    }

    @Override
    public String getPayName() {
        return mContext.getString(Utils.getStringId(mContext, "jy_pay_list_activity_ali_pay"));
    }

    @Override
    public int getPayType() {
        return PAY_TYPE_ALIPAY;
    }

    @Override
    public boolean checkPayAvailable() {
        return true;
    }

    @Override
    public int getPayIcon() {
        return Utils.getDrawableId(mContext, "jy_alipay_icon");
    }

    @Override
    public String getPayDesc() {
        return mContext.getString(Utils.getStringId(mContext, "jy_alipay_activity_alipay"));
    }

    /**
     * 在线程中执行支付操作
     *
     * @param payArgs
     */
    private void payInWorkerThread(final String payArgs) {

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                // Log.d(Log.TAG, "payArgs : " + payArgs);
                PayTask alipay = new PayTask((Activity) mContext);
                // 支付宝v2接口
                Map<String, String> result = alipay.payV2(payArgs,
                        true);
                Message msg = new Message();
                msg.what = Constants.SDK_PAY_FLAG;
                msg.obj = result;
                mPrivateHandler.sendMessage(msg);
            }
        };
        new Thread(payRunnable).start();
    }

    private void execPay(PayParams payParams) {
        Log.d(Log.TAG, "");
        // TODO : 本地组装支付参数，调试使用
        String payArgs = generateArgsLocal(payParams);
        if (!TextUtils.isEmpty(payArgs) && false) {
            payInWorkerThread(payArgs);
            return;
        }
        // 通过网络获取支付参数
        execPayAfterGetPayInfoFromServer(payParams);
    }

    public void execPayAfterGetPayInfoFromServer(PayParams payParams) {
        if (mPayFunction != null) {
            IPayRequest payRequest = mPayFunction.getPayRequest();
            if (payRequest == null) {
                mPayFunction.notifyPayResult(PayResult.PAY_FAILURE, mContext.getString(Utils.getStringId(mContext, "jy_fetch_payargs_error")), this);
                return;
            }
            final Alipay alipay = this;
            payRequest.queryAlipayArgs(payParams, new ResponseCallback<JSONObject>() {
                @Override
                public void onCallback(Response<JSONObject> response) {
                    String orderInfo = null;
                    String errorMsg = null;
                    try {
                        orderInfo = response.getObj().getString("orderinfo");
                    } catch (Exception e) {
                        errorMsg = response.getMsg();
                    }
                    if (!TextUtils.isEmpty(orderInfo)) {
                        payInWorkerThread(orderInfo);
                    } else {
                        if (TextUtils.isEmpty(errorMsg)) {
                            errorMsg = mContext.getString(Utils.getStringId(mContext, "jy_fetch_payargs_error"));
                        }
                        mPayFunction.notifyPayResult(PayResult.PAY_FAILURE, errorMsg, alipay);
                    }
                }
            });
        }
    }

    /**
     * 本地组装支付宝参数
     *
     * @param payParams
     * @return
     */
    private String generateArgsLocal(PayParams payParams) {
        if (payParams == null) {
            return null;
        }
        String price = payParams.getPrice();
        String subject = payParams.getSubject();
        String body = payParams.getBody();
        String order = payParams.getOrder();
        String attach = payParams.getAttach();
        return AlipayHelper.getSignedOrderInfo(price, subject, body, order, attach);
    }
}